package com.skstudio.nuprint;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;

import android.os.Environment;
import android.os.Handler;

public class PsFileMonitorService extends TimerTask {
	
	public final static String APP_ROOT = "nuprint";
	
	public interface OnFilesChangelistener {
		public void onFilesChanged(PsFileMonitorService service);
	}
	
	OnFilesChangelistener mListener = null;

	Handler mHandler = new Handler();
	
	Timer mTimer = new Timer();
	
	public PsFileMonitorService(OnFilesChangelistener listener) {
		mCurrSnapshot = find();
		mListener = listener;
		mTimer.schedule(this, 0, 1000);
	}
	
	public File[] getCurrentSnapshot() {
		File[] files = null;
		
		synchronized(this) {
			files = mCurrSnapshot.toArray(new File[mCurrSnapshot.size()]);
		}
		
		return files;
	}
	
	protected ArrayList<File> find() {
		ArrayList<File> list = new ArrayList<File>();
		
		File root = new File(Environment.getExternalStorageDirectory(), APP_ROOT);
		if (!root.exists()) return list;
		
		Iterator<File> it = FileUtils.iterateFiles(root, FileFilterUtils.suffixFileFilter("ps"), null);
		while (it.hasNext()) {
			File file = it.next();
			list.add(file);
		}
		
		return list;
	}

	ArrayList<File> mCurrSnapshot = null; 
	
	@Override
	public void run() {
		boolean bChanged = false;
		ArrayList<File> list = find();
		
		synchronized(this) {
			if (list.size() != mCurrSnapshot.size()) {
				bChanged = true;
			} else {
				for(int ii = 0; ii < list.size() && !bChanged; ii++) {
					File file = list.get(ii);
					
					boolean found = false;
					for(int jj = 0; jj < mCurrSnapshot.size() && !found; jj++) {
						File src = mCurrSnapshot.get(jj);
						try {
							if (src.getCanonicalPath().equals(file.getCanonicalPath()))
								found = true;
						} catch (IOException e) {
							found = true;
						}
					}
					
					if (!found) bChanged = true;
				}
			}
			
			if (bChanged) {
				mCurrSnapshot.clear();
				mCurrSnapshot = list;
			}
		}
		
		if (!bChanged) return;
		
		mHandler.post(new Runnable() {
				@Override
				public void run() {
					if (mListener != null)
						mListener.onFilesChanged(PsFileMonitorService.this);
				}	
			}
		);
	}
	
	public void stop() {
		mTimer.cancel();
	}
}